package id.co.shuba.spamobile.services;

import id.co.shuba.spamobile.App;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.transport.HttpsTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class WebServiceHelper {	
	private Context _ctx;

	private String _namespace;
	private String _path;
	private String _server;
	private int _port;
	private int _timeout;
	private boolean _isSecure;
	private boolean _bypassCertificate;

	public WebServiceHelper(Context ctx) {
		_ctx = ctx;
		//if (App.DEBUG) {
		init();
		//} else {
			//init_HardCode();
		//}		
	}
	
	public Context getContext() {
		return _ctx;
	}

	private void init() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(_ctx);
		_namespace = prefs.getString("ws_namespace", "http://tempuri.org/");
		_server = prefs.getString("ws_server", "moda.danamon.co.id");
		_path = prefs.getString("ws_path", "/SPAMOBILEWS/") + "ws.asmx";
		_port = Integer.parseInt(prefs.getString("ws_port", "443"));
		_timeout = Integer.parseInt(prefs.getString("ws_timeout", "300000"));
		_isSecure = prefs.getBoolean("ws_secure", true);
		_bypassCertificate = prefs.getBoolean("ws_bypass_certificate", true);
	}
	
	/*
	private void init_HardCode() {		
		_namespace = "http://tempuri.org/";
		_server = "modauat.danamon.co.id";
		_path =  "/SPAMOBILEWS_UAT/ws.asmx";
		_port = 444;
		_timeout = 5 * 60000;
		_isSecure = true;
		_bypassCertificate = true;
	}*/
	
	public Object Call(String methodName, Map<String, Object> properties) throws IOException, XmlPullParserException {
		return Call(methodName, properties, _timeout);
	}

	public Object Call(String methodName, Map<String, Object> properties, int timeout)
			throws IOException, XmlPullParserException {
		Log.d("WebServiceHelper", "Call: " + methodName);
		
		if (_bypassCertificate)
			trustEveryone();

		SoapObject request = new SoapObject(_namespace, methodName);		
		
		if (properties != null) {
			for (Map.Entry<String, Object> entry : properties.entrySet()) {
				if (App.DEBUG)
					Log.d("WebServiceHelper", "addParameter: [" + entry.getKey() + ", "+entry.getValue()+"]");
				request.addProperty(entry.getKey(), entry.getValue());
			}
		}

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		envelope.dotNet = true;
		envelope.setOutputSoapObject(request);				

		if (_isSecure) {
			HttpsTransportSE httpTransport = new HttpsTransportSE(_server,
					_port, _path, timeout);
			httpTransport.call(_namespace + methodName, envelope);
		} else {
			HttpTransportSE httpTransport = new HttpTransportSE(
					"http://" + _server + _path, timeout);
			httpTransport.call(_namespace + methodName, envelope);
		}

		return envelope.getResponse();
	}	

	public static void trustEveryone() {
		try {
			HttpsURLConnection
					.setDefaultHostnameVerifier(new HostnameVerifier() {
						public boolean verify(String hostname,
								SSLSession session) {
							return true;
						}
					});

			SSLContext context = SSLContext.getInstance("TLS");
			context.init(null, new X509TrustManager[] { new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return new X509Certificate[0];
				}
			} }, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(context
					.getSocketFactory());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}	
}
